package com.ksana.orm.core.io.impl;

import com.ksana.core.DefaultResourceLoader;
import com.ksana.orm.core.io.Reader;
import lombok.SneakyThrows;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertiesReader implements Reader {
    @SneakyThrows
    @Override
    public Map<String, Object> reader(String path) {
        InputStream inputStream = new DefaultResourceLoader().getResource(path).getInputStream();
        Map<String, Object> map = new HashMap<>();
        try {
            Properties properties = new Properties();
            properties.load(inputStream);
            Enumeration propertiesEnumeration = properties.propertyNames();
            while (propertiesEnumeration.hasMoreElements()) {
                String key = (String) propertiesEnumeration.nextElement();
                map.put(key, properties.get(key));
            }

            return map;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream == null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }
}
